package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.domain.Answer;
import com.example.domain.Question;
import com.example.mapper.AnswerMapper;
import com.example.service.AnswerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author DPH
* @description 针对表【tbl_answer】的数据库操作Service实现
* @createDate 2022-11-23 16:19:41
*/
@Service
public class AnswerServiceImpl extends ServiceImpl<AnswerMapper, Answer>
    implements AnswerService{
    @Autowired
    private AnswerMapper answerMapper;

    @Override
    public boolean saveAnswer(Answer answer) {
        return answerMapper.insert(answer) > 0;
    }

    @Override
    public boolean modify(Answer answer) {
        return answerMapper.updateById(answer) > 0;
    }

    @Override
    public Map<Integer,Map<String,Integer>> getAnswer(List<Question> questions) {
        Map<Integer,Map<String,Integer>> map = new HashMap<>();
        for (Question question : questions) {
            QueryWrapper<Answer> wrapper = new QueryWrapper<>();
            wrapper.eq("question_id",question.getQuestionId());
            List<Answer> answers = answerMapper.selectList(wrapper);
            Map<String,Integer> answerMap = new HashMap<>();
            for (Answer answer : answers) {
                String answerContent = answer.getContent();
                if (answerMap.containsKey(answerContent)){
                    answerMap.put(answerContent,answerMap.get(answerContent)+1);
                }else {
                    answerMap.put(answerContent,1);
                }
            }
            map.put(question.getQuestionNum(),answerMap);
        }
        return map;
    }

    @Override
    public Map<Integer, List<String>> getClozeAnswer(List<Question> questions) {
        Map<Integer,List<String>> map = new HashMap<>();
        for (Question question : questions) {
            QueryWrapper<Answer> wrapper = new QueryWrapper<>();
            wrapper.eq("question_id",question.getQuestionId());
            List<Answer> answers = answerMapper.selectList(wrapper);
            List<String> answerList = new ArrayList<>();
            if (answers.size() > 0){
                for (Answer answer : answers) {
                    answerList.add(answer.getContent());
                }
            } else {
                return null;
            }
            map.put(question.getQuestionNum(),answerList);
        }
        return map;
    }

    @Override
    public boolean delete(Integer questionId) {
           QueryWrapper<Answer> wrapper = new QueryWrapper<>();
            wrapper.eq("question_id",questionId);
            return answerMapper.delete(wrapper) > 0;
    }
}




